﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NewRetail.Application.Components.Warehouse;
using NewRetail.Application.Components.Warehouse.Entity;
using NewRetail.Application.Core;
using System;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;

namespace NewRetail.Api.Controllers
{
    [NewRetailRoute("discount")]
    public class PromoteSaleDiscountController : ReceiptsBaseController<PromoteSalesDiscount>
    {
        private readonly IDiscountService _discountService;
        public PromoteSaleDiscountController(IDiscountService discountService)
        {
            this._discountService = discountService;
        }

        public override async Task<ResponseEntity<PagedResultDto<PromoteSalesDiscount>>> QueryPaging([FromBody] PagingRequestDto dto)
        {
            var data = await base.QueryPaging(dto);

            if (data.Data?.Items?.Any() ?? false)
            {
                //将显示为0，即false的记录剔除
                data.Data.Items = data.Data.Items.Where(x => x.isShow == true).ToArray();
                data.Data.Items = await this._discountService.AttachWarehouse(data.Data.Items.ToArray());
                data.Data.Items = await this._discountService.AttachGoodsCategory(data.Data.Items.ToArray());
                data.Data.Items = await this._discountService.AttachSingleGoods(data.Data.Items.ToArray());
                
                data.Data.TotalCount = data.Data.Items.Count;
            }

            return data;
        }

        [HttpPost("save-multiple")]
        public async Task<ResponseEntity<PromoteSalesDiscount[]>> SaveMultiple([FromBody] ReceiptNoItemsDto<PromoteSalesDiscount> data)
        {
            var res = await this.Repo.SaveReceiptItems(this.HttpContext.RequestServices, data, "PSD");
            return new ResponseEntity<PromoteSalesDiscount[]>().SetData(res.Items);
        }

        [HttpPost("query-by-receipt-no")]
        public async Task<ResponseEntity<PromoteSalesDiscount[]>> QueryByReceiptNo([FromBody] ReceiptNoDto dto)
        {
            dto.Should().NotBeNull();
            dto.receiptNo.Should().NotBeNullOrEmpty();
            var query = this.SingleStoreService.ApplyToQueryable(this.Repo);
            var data = await query.Where(x => x.receiptNo == dto.receiptNo).ToArrayAsync();

            return new ResponseEntity<PromoteSalesDiscount[]>().SetData(data);
        }
    }
}
